import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:provide/provide.dart';
import 'package:url_launcher/url_launcher.dart';

import '../../../common/action/index.dart';
import '../../../common/global/global.dart';
import '../../../http/apis/common.dart';
import '../../../http/models/bannerModel.dart';
import '../../../http/models/recommendModel.dart';
import '../../../states/states_model/user.dart';
import '../../../widgets/easyRefreshWidget.dart';
import '../../../widgets/tipsDialog.dart';
import 'Bloc/HotBloc.dart';

class Hot extends StatefulWidget {
  Hot({Key key}) : super(key: key);

  @override
  _HotState createState() => _HotState();
}

class _HotState extends State<Hot> {
  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) => HotBloc(),
      child: Builder(
        builder: (context) {
          return EasyRefresh(
            header: EasyRefreshSetting.header,
            footer: EasyRefreshSetting.footer,
            onRefresh: () async {
              context.bloc<HotBloc>().add(HotEvent.refresh);
            },
            onLoad: () async {
              context.bloc<HotBloc>().add(HotEvent.load);
            },
            child: SingleChildScrollView(
              child: Column(
                children: [
                  _Banner(),
                  _Anchors(),
                ],
              ),
            ),
          );
        },
      ),
    );
  }
}

class _Banner extends StatefulWidget {
  _Banner({Key key}) : super(key: key);

  @override
  __BannerState createState() => __BannerState();
}

class __BannerState extends State<_Banner> {
  List<BannerModel> list = [];

  @override
  void initState() {
    super.initState();
    CommonApis.adpicture().then((res) {
      if (!mounted) return;
      list = res;
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: px(234),
      padding: EdgeInsets.symmetric(vertical: px(16)),
      child: Builder(
        builder: (context) {
          if (list.length > 0) {
            return Swiper(
              onTap: (int i) async {
                final user = Provide.value<UserState>(context);
                final isLogin = user?.info != null;

                if (!isLogin) {
                  TipsDialog.login(
                    context,
                    () {
                      goPage(context, '/phoneLogin');
                    },
                  );
                  return;
                }

                String url = list[i].adHref;
                if (url.contains('http') && await canLaunch(url)) {
                  return launch(url);
                }
                if (list[i].adHref != null && list[i].adHref.length > 0) {
                  return goPage(context, list[i].adHref);
                }
              },
              itemBuilder: (BuildContext context, int i) {
                return ClipRRect(
                  borderRadius: BorderRadius.circular(px(15)),
                  child: Image.network(
                    "${list[i].adUrl}?imageView2/2/h/230",
                    fit: BoxFit.fill,
                  ),
                );
              },
              autoplay: true,
              itemCount: list.length,
              viewportFraction: 0.9,
              scale: 0.9,
            );
          }
          return SizedBox.shrink();
        },
      ),
    );
  }
}

class _Anchors extends StatelessWidget {
  const _Anchors({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<HotBloc, List<RecommendModel>>(
      builder: (context, state) {
        return Column(
          children: List.generate(
            state.length,
            (i) => GestureDetector(
              onTap: () {
                final user = Provide.value<UserState>(context);
                final info = user.info;
                final isLogin = info != null;
                if (isLogin) {
                  goPage(
                    context,
                    '/anchorInfo',
                    param: {'token': state[i].memberToken},
                  );
                } else {
                  TipsDialog.login(
                    context,
                    () {
                      goPage(context, '/phoneLogin');
                    },
                  );
                }
              },
              child: Container(
                width: double.infinity,
                height: px(600),
                margin: EdgeInsets.only(bottom: px(16)),
                child: Stack(
                  children: [
                    SizedBox(
                      width: double.infinity,
                      height: px(600),
                      child: CachedNetworkImage(
                        imageUrl: "${state[i].firstimg}?imageView2/2/w/750",
                        fit: BoxFit.cover,
                        errorWidget: (context, url, error) {
                          return Config.errorNetImage;
                        },
                      ),
                    ),
                    Positioned(
                      top: px(20),
                      left: px(24),
                      child: _Price(state[i]),
                    ),
                    Positioned(
                      top: px(20),
                      right: px(24),
                      child: _OnlineStatus(state[i]),
                    ),
                    Positioned(
                      bottom: px(20),
                      left: px(25),
                      child: _Info(state[i]),
                    ),
                  ],
                ),
              ),
            ),
          ),
        );
      },
    );
  }
}

class _OnlineStatus extends StatelessWidget {
  final RecommendModel info;

  const _OnlineStatus(this.info, {Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      height: px(48),
      padding: EdgeInsets.symmetric(horizontal: px(18)),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.all(Radius.circular(px(24))),
        color: col("04040f").withOpacity(.4),
      ),
      child: Row(
        children: <Widget>[
          Container(
            width: px(12),
            height: px(12),
            margin: EdgeInsets.only(right: px(8)),
            decoration: BoxDecoration(
              color: CommonAction.checkAnchorStatus(
                info.disturb,
                info.online,
              ).color,
              borderRadius: BorderRadius.circular(px(6)),
            ),
          ),
          Text(
            "${CommonAction.checkAnchorStatus(
              info.disturb,
              info.online,
            ).text}",
            style: TextStyle(
              color: Colors.white,
              fontSize: px(24),
            ),
          ),
        ],
      ),
    );
  }
}

class _Info extends StatelessWidget {
  final RecommendModel info;

  const _Info(this.info, {Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            info.memberNickname,
            style: TextStyle(
              color: Colors.white,
              fontSize: px(32),
              fontWeight: FontWeight.bold,
              shadows: [
                Shadow(
                  color: Colors.black26,
                  blurRadius: 1,
                  offset: Offset(1, 1),
                ),
              ],
            ),
          ),
          SizedBox(height: px(10)),
          Text(
            info.anchorSign,
            style: TextStyle(
              color: Colors.white.withOpacity(.9),
              fontSize: px(24),
              shadows: [
                Shadow(
                  color: Colors.black26,
                  blurRadius: 1,
                  offset: Offset(1, 1),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

class _Price extends StatelessWidget {
  final RecommendModel info;

  const _Price(this.info, {Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      height: px(48),
      padding: EdgeInsets.symmetric(horizontal: px(10)),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.all(Radius.circular(px(24))),
        gradient: LinearGradient(
          colors: [
            col("ffda2a"),
            col("f99705"),
          ],
        ),
      ),
      child: Row(
        children: [
          Image.asset(
            "assets/images/icon/star.png",
            width: px(30),
            height: px(30),
          ),
          SizedBox(width: px(5)),
          Text(
            "${info.timePrice}金币/分钟",
            style: TextStyle(
              color: Colors.white,
              fontSize: px(24),
            ),
          ),
        ],
      ),
    );
  }
}
